#!/usr/bin/python

#Audio Tools, a module and set of tools for manipulating audio data
#Copyright (C) 2007  Brian Langenberger

#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


import os
import sys
import audiotools
import optparse
import tempfile
import subprocess

MAX_CPUS = audiotools.MAX_JOBS

def convert_to_wave(audiofile,wave_filename):
    if ((audiofile.sample_rate() == 44100) and
        (audiofile.channels() == 2) and
        (audiofile.bits_per_sample() == 16)):  #already CD quality
        audiofile.to_wave(wave_filename)
    else:                              #convert to CD quality
        pcm = audiotools.PCMConverter(audiofile.to_pcm(),44100,2,16)
        audiotools.WaveAudio.from_pcm(wave_filename,pcm)
        pcm.close()

    print (u"* %s" % (audiofile.filename.decode(audiotools.FS_ENCODING))
           ).encode(audiotools.IO_ENCODING,'replace')

if (__name__ == '__main__'):
    if (not audiotools.BIN.can_execute(audiotools.BIN['cdrecord'])):
        print >>sys.stderr,'*** Unable to find "cdrecord" executable'
        print >>sys.stderr,'Please install "cdrecord" to burn CDs'
        sys.exit(1)

    parser = optparse.OptionParser(
        usage="%prog [options] <track 1> [track 2] ...",
        version="Python Audio Tools %s" % (audiotools.VERSION))

    parser.add_option("-c","--cdrom",dest="dev",
                      help="cdrom device to use")

    parser.add_option("-s","--speed",dest="speed",
                      help="the speed to burn the CD at",type="int")

    parser.add_option('-j','--joint',
                      action='store',
                      type='int',
                      default=MAX_CPUS,
                      dest='max_processes',
                      help='the maximum number of processes to run at a time')

    (options,args) = parser.parse_args()

    if (options.max_processes < 1):
        print >>sys.stderr,'*** You must run at least 1 process at a time'
        sys.exit(1)
    else:
        max_processes = options.max_processes

    audiofiles = audiotools.open_files(args,sorted=False)

    if (len(args) < 1):
        print >>sys.stderr,"*** You must specify at least one audio file"
        sys.exit(1)

    exec_args = [audiotools.BIN['cdrecord']]

    if (options.speed != None):
        exec_args.append("-speed")
        exec_args.append(str(options.speed))

    if (options.dev != None):
        exec_args.append("-dev")
        exec_args.append(options.dev)

    exec_args.append("-tao")
    exec_args.append("-pad")
    exec_args.append("-audio")

    temp_pool = []
    wave_files = []
    queue = audiotools.ExecQueue()

    print >>sys.stderr,"*** Converting audio files"
    for audiofile in audiofiles:
        if (isinstance(audiofile,audiotools.WaveAudio)):
            wave_files.append(audiofile.filename)
        else:
            f = tempfile.mkstemp(suffix='.wav')
            temp_pool.append(f)
            wave_files.append(f[1])
            queue.execute(convert_to_wave,
                          (audiofile,f[1]))

    queue.run(max_processes)

    exec_args += wave_files
    subprocess.call(exec_args)

    for (fd,f) in temp_pool:
        os.close(fd)
        os.unlink(f)
    del(temp_pool)

